<template>
  <div class="register-container">
    <div class="registesr-form-wrap">
      <div class="main">
        <img
          src="https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg"
          alt
          class="log"
        />
        <h3>让科研不在"孤岛" · MAKE MACHINE WISE</h3>
      </div>
      <el-form
        :model="resgisterForm"
        :rules="rules"
        ref="resgisterForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="resgisterForm.userName"
            placeholder="昵称"
            @blur="validateHandler('userName')"
          />
        </el-form-item>
        <el-form-item prop="userTel">
          <el-input
            v-model="resgisterForm.userTel"
            @change="existUsername"
            placeholder="手机号/邮箱"
            autocomplete="new-password"
            @blur="validateHandler('username')"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="resgisterForm.password"
            show-password
            placeholder="密码(6~16 个字符，数字、字母或标点符号的组合)"
            autocomplete="new-password"
            @blur="validateHandler('password')"
          />
        </el-form-item>
        <el-form-item prop="password2">
          <el-input
            type="password"
            v-model="resgisterForm.password2"
            show-password
            placeholder="确认密码"
            autocomplete="new-password"
            @blur="validateHandler('password2')"
          />
        </el-form-item>
          <el-form-item prop="userEmail">
          <el-input
            v-model="resgisterForm.userEmail"
            placeholder="邮箱"
            @blur="validateHandler('userEmail')"
          />
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="resgisterForm.code"
            autocomplete="off"
            placeholder="验证码"
            style="width: 250px"
            @blur="validateHandler('code')"
          />
          <el-button type="primary" :disabled="isDisabled" class="sendCode">
            <span v-if="isCodeShow" @click="sendEmailCode()">获取验证码</span>
            <span v-else>{{ count }} 秒后重新获取</span>
          </el-button>
        </el-form-item>
        <!-- <el-form-item prop="imgCode" style="">
            <el-input   placeholder="图片验证码" v-model="resgisterForm.imgCode" style="top:-14px;width:250px;" @blur="validateHandler('imgCode')"/>
            <img :src="imgCode" onclick="this.src=this.src+'?'+Math.random();" title="点击刷新" class="imgCode"> 
        </el-form-item> -->
        <el-form-item prop="agree">
          <el-checkbox
            v-model="resgisterForm.agree"
            @change="validateHandler('agree')"
            >我已阅读并同意
            <a href="/passport/deal" target="_blank">《科研用户使用协议》</a>
            和 <a href="/passport/privacy" target="_blank">《科研隐私政策》</a>
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button @click="onRegister" style="width: 100%">注册</el-button>
          <a @click="turnLogin" class="turnLogin"
            >已有账号，直接登录 <i class="el-icon-arrow-right"></i
          ></a>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: "Register",
  data() {
    return {
      imgCode: "/api/account/code/get",
      isCodeShow: true,
      count: 0,
      timer: {},
      // buttonText: '获取验证码',
      existUsernameFlag: 0,
      resgisterForm: {
        userName: "",
        userTel: "",
        password: "",
        password2: "",
        userEmail:"",
        code: "",
        imgCode: "",

        agree: false,
      },
      rules: {
        userName: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
         userEmail: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
        ],
        userTel: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            validator: this.validateUsername,
            min: 5,
            max: 14,
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "6~16 个字符，数字、字母或标点符号的组合",
            trigger: "blur",
          },
        ],
        password2: [
          { required: true, message: "确认密码不能为空", trigger: "change" },
          { validator: this.validatePassword2, trigger: "blur" },
        ],
        code: [
          { required: true, message: "验证码不能为空", trigger: "change" },
        ],
        imgCode: [
          { required: true, message: "图片验证码不能为空", trigger: "change" },
        ],
        agree: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                // 验证通过
                callback();
              } else {
                // 验证失败
                callback(new Error("请同意用户协议"));
              }
            },
            message: "请勾选用户协议",
            trigger: "blur",
          },
        ],
      },
      flag: true,
      timer: 0,
      count: 0,
    };
  },
  computed: {
    isDisabled() {
      return Boolean(!this.resgisterForm.userTel);
    },
  },
  methods: {
    validateHandler(fieldName) {
      this.$refs.resgisterForm.validateField(fieldName);
    },
    // <!--提交注册-->
    onRegister() {
        this.$axios
          .post("https://localhost:44396/api/service/user/register", this.resgisterForm)
          .then((res) => {
            console.log(res.data);
            if ((res.data.state == 200)) {
              this.$message.success("操作成功");
              this.$router.push("/Logins");
            } else if ((res.data.state == 400)) {
              this.$message.error("注册失败");
              return;
            }
          })
          .catch((error) => {
            let errMsg = error.response.data.msg;
            this.$message.error(errMsg);
          });
 
    },
    getQueryParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    },
    turnLogin() {
     
      this.$router.push("Logins");
    },
    existUsername() {
      // 检查用户名是否重名
      let id = this.resgisterForm.id || 0;
      this.axios
        .get("/api/account/user/exist/" + id + "/" + this.resgisterForm.userTel)
        .then((res) => {
          let exist = res.data.data.exist;
          // 0=待验证，1=验证通过（用户名不存在），2=验证失败（用户名已存在）
          this.existUsernameFlag = exist ? 2 : 1;
          this.$refs.resgisterForm.validateField("userTel", (valid) => {});
        })
        .catch(console.error);
    },
    sendEmailCode() {
      let TIME_COUNT = 60;
      if (Object.keys(this.timer).length == 0) {
        this.count = TIME_COUNT;
        this.isCodeShow = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.isCodeShow = true;
            clearInterval(this.timer);
            this.timer = {};
          }
        }, 1000);
      }
      console.log(this.resgisterForm.userTel);
      //var params = {account:this.resgisterForm.username}
      this.$axios
        (
          "https://localhost:44396/api/Service/login?args=" +
            this.resgisterForm.userTel
        )
        .then((res) => {
          this.$message.success("验证码已发送");
        })
        .catch((err) => {
          this.$message.error("发送失败");
        });
    },

    validateUsername(rule, value, callback) {
      let patternMail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      let patternMobile = /^[1][3,4,5,6.7,8,9][0-9]{9}$/;
      if (value.match(patternMail) || value.match(patternMobile)) {
        if (this.existUsernameFlag == 1) {
          // 通过验证
          callback();
        } else if (this.existUsernameFlag == 2) {
          callback(new Error("账号已存在"));
        } else {
          callback();
        }
      } else {
        callback(new Error("邮箱/手机号"));
      }
    },
    validatePassword(rule, value, callback) {
      if (
        "***" != value &&
        (value.length < rule.min || value.length > rule.max)
      ) {
        callback(new Error(rule.message));
      } else if (
        "***" != value &&
        !value.match(/[~!@#$%^&*\_.0-9a-zA-Z]{6,16}$/)
      ) {
        callback(new Error("密码不符合要求"));
      } else {
        callback();
      }
    },
    validatePassword2(rule, value, callback) {
      if (value != this.resgisterForm.password) {
        callback(new Error("两次密码输入不一致"));
      } else {
        callback();
      }
    },
  },
};
</script>

<style scoped >
.registesr-form-wrap {
  margin: 50px auto;
  width: 420px;
  border: 1px solid #a0b1c4;
  border-radius: 5px;
  box-shadow: 0px 0px 20px #f3f3f3;
  padding: 0px 50px 10px;
}
.main .log {
  width: 143px;
  height: 53px;
  margin-top: 20px;
  margin-left: 111px;
}
.main h3 {
  font-size: 15px;
  display: flex;
  justify-content: center;
}
.el-button,
.code-btn:hover {
  background: #a93ac2;
  border-color: #a93ac2;
  color: white;
}
.code >>> .el-form-item__content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.el-form-item /deep/.el-form-item__content {
  height: 40px !important;
}
.code button {
  margin-left: 20px;
  width: 130px;
  /* text-align: center; */
}
.el-button:first-child {
  width: 118px;
}
.turnLogin {
  float: right;
  font-size: 15px;
}
a,
.turnLogin,
.main h3,
i {
  text-decoration: none;
  color: #a93ac2;
}
.imgCode {
  width: 117px;
  height: 40px;
  margin-left: 51px;
}
a {
  cursor: pointer;
}
.sendCode {
  float: right;
  height: 38px;
  width: 118px;
}
</style>
